package coroutines;

import java.util.concurrent.CompletableFuture;

public class SampleCode2 {

    public void changeProductImage() {
        for (int i = 0; i < 10000; i++) {
            int productId = i;
            CompletableFuture<Product> productFuture = CompletableFuture.supplyAsync(() -> {
                Product p = retriveProduct(productId);
                return p;
            });
            productFuture.whenComplete((product, e) -> {
                CompletableFuture<String> imageFuture = CompletableFuture.supplyAsync(() -> {
                    String updateImageUrl = updateImage(product.imageUrl);
                    return updateImageUrl;
                });
                imageFuture.whenComplete((image, ee) -> {
                    product.imageUrl = image;
                    updateProduct(product);
                });
            });
        }
    }

    private void updateProduct(Product p) {
        // IO操作，耗时200毫秒
    }

    private String updateImage(String imageUrl) {
        // 图片压缩算法，耗时500毫秒
        return null;
    }

    private Product retriveProduct(int productId) {
        // // IO操作，耗时100毫秒
        return null;
    }

    class Product {
        String imageUrl;
    }
}
